package design.pattern.Lu14IteratorPattern;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @program JavaBase
 * @description: 迭代器模式
 * @author: zhanglu
 * @create: 2020-04-09 17:38:00
 */
public class IteratorPattern {

    public static void main(String[] args) {

        Project01 project01 = new Project01();

        for (int i = 0; i < 5; i++) {
            project01.add("项目" + i, i);
        }

        IProjectIterator iProjectIterator = project01.iterator();
        while (iProjectIterator.hasNext()){
            IProject01 p = (IProject01) iProjectIterator.next();
            System.out.println(p.projectInfo());
        }

    }

}

interface IProjectIterator extends Iterator {

}

interface IProject01{
    String projectInfo();
    void add(String name, int count);
    IProjectIterator iterator();
}

class Project01 implements IProject01{

    private List<IProject01> project01List = new CopyOnWriteArrayList<>();

    private String name;
    private int count;

    public Project01(){}

    public Project01(String name, int count){
        this.name = name;
        this.count = count;
    }

    @Override
    public String projectInfo() {
        String str = "项目名称：" + this.name + "\t项目数量：" + this.count;
        return str;
    }

    @Override
    public void add(String name, int count) {
        project01List.add(new Project01(name, count));
    }

    @Override
    public IProjectIterator iterator() {
        return new ProjectIterator(this.project01List);
    }
}

class ProjectIterator implements IProjectIterator{

    private List<IProject01> project01List = new CopyOnWriteArrayList<>();
    private int currentItem = 0;


    public ProjectIterator(List<IProject01> project01List){
        this.project01List = project01List;
    }


    @Override
    public boolean hasNext() {
        return this.currentItem < this.project01List.size();
    }

    @Override
    public IProject01 next() {
        return this.project01List.get(this.currentItem++);
    }

}
